package basic.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SocketNoneBlockNIOServer {

    public void server(){

        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress("localhost",30401));
            Selector selector  = Selector.open();
            serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
            while (selector.select()>0){
                System.out.println("selector:selector:"+selector.select());
                Iterator<SelectionKey> sks = selector.selectedKeys().iterator();
                while(sks.hasNext()){
                    SelectionKey sk = sks.next();
                    //System.out.println("interestOps:"+sk.interestOps());
                    //ystem.out.println("channel_hashcode:"+sk.channel().hashCode());
                    //System.out.println("selector_hashcode:"+sk.selector().hashCode());
                    if (sk.isAcceptable()){
                        SocketChannel sChanel = serverSocketChannel.accept();
                        sChanel.configureBlocking(false);
                        sChanel.register(selector,SelectionKey.OP_READ);

                    }else if (sk.isReadable()){
                        SocketChannel socketChannel = (SocketChannel) sk.channel();
                        ByteBuffer bys = ByteBuffer.allocate(1024);
                        int len=0;
                        while ((len = socketChannel.read(bys))>0){
                            bys.flip();
                            System.out.println(new String(bys.array(),0,len));
                            bys.clear();
                        }
                    }

                    sks.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new SocketNoneBlockNIOServer().server();
    }

}
